#!/usr/bin/python3
import sys
import re
from collections import deque

def add_to_queue(queue, prefix, src, snk, state):
    for target in snk:
        print(f'{prefix}{src[:5]}:{"\t" if len(src) < 2 else ""}\t{"high" if state else "low "}\t-> {target}')
        queue.append((target, state))

def flipflop_regs(regs, flipflops):
    return {src: regs[src] for src in flipflops}

def part1():
    print('part 1')
    regs = {}
    flipflops = {}
    conjunctions = {}
    for line in map(str.strip, sys.stdin):
        found = re.findall(r'([%&])?([a-z]+) -> ([a-z, ]+)', line)[0]
        prefix, src, snk = found[0], found[1], found[2].split(', ')
        regs[src] = False
        if prefix == '%' or prefix == '':
            flipflops[src] = (prefix, snk)
        else:
            conjunctions[src] = ('&', snk, [])
    for flop in flipflops:
        for target in flipflops[flop][1]:
            for con in conjunctions.keys():
                if con == target:
                    conjunctions[con][2].append(flop)
    print(f'regs:         {regs}')
    print(f'flipflops:    {flipflops}')
    print(f'conjunctions: {conjunctions}')
    pulses = {True: 0, False: 0}
    initial_flipflop_regs = flipflop_regs(regs, flipflops)
    for i in range(1000):
        print(f'\n@press = {i}')
        queue = deque()
        queue.append(('broadcaster', False))
        while len(queue) > 0:
            src, state = queue.popleft()
            if src in flipflops:
                prefix, snk = flipflops[src]
            elif src in conjunctions:
                prefix, snk, dep = conjunctions[src]
            pulses[state] += 1
            if src not in regs:
                continue
            if prefix == '':
                add_to_queue(queue, prefix, src, snk, state)
            elif prefix == '%':
                if state == False:
                    regs[src] = not regs[src]
                    add_to_queue(queue, prefix, src, snk, regs[src])
            elif prefix == '&':
                value = not all([regs[dep] for dep in conjunctions[src][2]])
                regs[src] = value
                add_to_queue(queue, prefix, src, snk, value)
        new_flipflop_regs = flipflop_regs(regs, flipflops)
        if new_flipflop_regs == initial_flipflop_regs:
            print(pulses)
            at = i + 1
            remaining = 1000 % at
            pulses[True] *= (1000 - remaining) // at
            pulses[False] *= (1000 - remaining) // at
            break
    print(f'{pulses} yields {pulses[True] * pulses[False]}')

def part2():
    print('part 2')

if sys.argv[1] in '1':
    part1()
else:
    part2()
